# -*- coding: utf-8 -*-

# @Project : UI_DDTFrameWork
# @Author  : Mr.Deng
# @Time    : 2021/9/18 23:07

"""
Select 下拉框处理，包括：索引查找、文本查找、随机查找、属性查找
"""

from selenium.webdriver.support.select import Select as _Select

from common.seleniumLibrary.base import Base
from common.tools.decorator import error_collection

import random


class Select(Base):

    @error_collection
    def select_by_text(self, elementPath: tuple, text: str, tagName: str = None, isFuzzy: bool = False):
        """
        按页面显示文字选择下拉元素
        :param tagName: 下拉选项标签
        :param isFuzzy: 是否开启模糊匹配，默认关闭
        :param elementPath: 下拉框元素路径
        :param text: 被选中的文本信息
        :return:
        """
        # 获取下拉框元素定位
        select = _Select(self._find_element_presence(elementPath))
        if isFuzzy:
            # 获取全部下拉选项列表
            selectList = self._find_elements_by_tag_name(elementPath, tagName)
            for tag in selectList:
                self.sleep(1)
                tagText = tag.text
                if text in tagText or tagText in text:
                    select.select_by_visible_text(tagText)
                    break
            else:
                raise NameError(f"模糊匹配的选项：{text} 下拉列表中不存在！！！")
        else:
            select.select_by_visible_text(text)
        self.Log.info(f"展开下拉框并根据选项文本信息选中: {text}")

    @error_collection
    def select_by_index(
            self, elementPath: tuple, tagName: str = None, index: int = None, isRandom: bool = False):
        """
        按页面显示索引选择下拉元素
        :param elementPath: 下拉框元素路径
        :param tagName: 下拉选项标签
        :param index: 要选的索引
        :param isRandom: 是否开启随机匹配，默认关闭
        :return:
        """
        randomSelectNum = None
        # 获取下拉框元素定位
        select = _Select(self._find_element_presence(elementPath))
        if isRandom:
            try:
                # 获取全部下拉选项总数量
                selectCount = self._find_elements_by_tag_name(elementPath, tagName)
                # 随机选中一个索引
                randomSelectNum = random.randint(0, len(selectCount) - 1)
                select.select_by_index(randomSelectNum)
                self.Log.info(f"展开下拉框并根据选项索引信息随机选中: {randomSelectNum}")
            except:
                raise Exception(f"下拉选项中不存在该索引：{randomSelectNum} ！！！ ")
        else:
            select.select_by_index(index)
            self.Log.info("展开下拉框并根据选项索引信息选中: {}".format(index))

    @error_collection
    def select_by_value(
            self, elementPath: tuple, value: str, tagName: str = None, isFuzzy: bool = False):
        """
        根据下拉列表选项中的标签的value属性值进行选择
        :param elementPath: 下拉框元素路径地址
        :param value: 被选中的标签属性值
        :param tagName: 标签名称
        :param isFuzzy: 是否执行模糊匹配
        :return:
        """
        # 获取下拉框元素定位
        select = _Select(self._find_element_presence(elementPath))
        if isFuzzy:
            # 获取全部下拉选项总数量
            selectList = self._find_elements_by_tag_name(elementPath, tagName)
            for tag in selectList:
                self.sleep(1)
                attrNameStr = tag.get_attribute("value")
                if value in attrNameStr or attrNameStr in value:
                    select.select_by_value(attrNameStr)
                    break
            else:
                raise NameError(
                    f"根据标签：{tagName} 值属性：value 模糊匹配的选项：{value} 下拉列表中不存在！！！")
        else:
            select.select_by_value(value)
        self.Log.info("展开下拉框并根据选项value属性值信息选中: {}".format(value))

    @error_collection
    def operate_not_select_box(
            self, elementPath: tuple, tagName: str, text: str = None, isRandom: bool = False):
        """
        操作非select下拉选择框操作, 遍历下拉列表中的文本数据匹配关键字
        :param elementPath: 下拉框父级元素路径
        :param tagName: 下拉列表标签名称
        :param text: 所要选中的文本信息
        :param isRandom: 是否开启随机选择模式
        :return:
        """
        selectText = None
        # 获取子集所有标签列表
        childElementList = self._find_elements_by_tag_name(elementPath, tagName)
        if isRandom:
            # 开启随机选择模式
            randomSelectNum = random.randint(0, len(childElementList) - 1)
            try:
                self.sleep(1)
                selectText = childElementList[randomSelectNum].text
                childElementList[randomSelectNum].click()
            except:
                raise Exception(f"非select随机选中列表选项：{selectText} 失败！！！")
            else:
                self.Log.info(f"非select下拉框，根据选项文本信息随机选中: {selectText}")
        else:
            # 按标签文本模糊匹配
            for child in childElementList:
                self.sleep(1)
                childText = child.text
                if text in childText or childText in text:
                    try:
                        child.click()
                        break
                    except:
                        raise Exception(f"点击选中列表选项：{text} 失败！！！")
            else:
                raise Exception(f"非select下拉列表中没有找到匹配的选项：{text} ")
            self.Log.info(f"非select下拉框，根据选项文本模糊匹配信息选中: {text}")


# if __name__ == '__main__':
#     from common.seleniumLibrary import PySelenium
#     from selenium.webdriver.common.by import By
#
#     element = PySelenium()
#     element.open_url("https://www.baidu.com/")
#     element.move_on_element(elementPath=(By.XPATH, '//*[@id="s-usersetting-top"]'))
#     element.move_and_click(elementPath=(By.XPATH, '//a[contains(text(),"搜索设置")]'))
#     element.click(elementPath=(By.XPATH, '//*[@href="#advanced"]'))
#     element.click(elementPath=(By.XPATH, '(//div[@class="c-select-selection"])[1]'))
#     element.operate_not_select_box(elementPath=(By.XPATH, '(//div[@class="c-select-dropdown-list"])[1]'), tagName='p',
#                                    isRandom=True)
